<template>
  <van-button
    @click="followClick"
    v-if="value"
    class="follow-btn"
    round
    size="small"
    :loading="isLoading"
    >已关注</van-button
  >
  <van-button
    @click="followClick"
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="isLoading"
    >关注</van-button
  >
</template>
<script>
import { addUserFollowApi, delUserFollowApi } from "@/api/Article";
// Vue 里面如何定义一个递归组件
// 一个递归式必须要有name的！
export default {
  name: "FollowUser",
  props: {
    // 是否被关注
    value: {
      type: Boolean,
      required: true,
    },
    // 作者ID
    authorId: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      isLoading: false,
    };
  },
  methods: {
    // 关注点击事件
    async followClick() {
      // 判断是否登录
      if (!this.$store.getters.token) return this.$toast.fail("请登录");
      // 已登录了
      this.isLoading = true;
      try {
        if (this.value) {
          // 已关注，要取消
          await delUserFollowApi(this.authorId);
        } else {
          // 未关注，则关注
          await addUserFollowApi({
            target: this.authorId,
          });
        }
        // 提示成功
        this.$toast.success(this.value ? "取消成功" : "关注成功");

        // 视图的更新
        this.$emit("input", !this.value);
      } catch (error) {
        this.$toast.fail("操作失败");
        console.log(error);
      }
      this.isLoading = false;
    },
  },
};
</script>
<style scoped lang="less"></style>
